﻿using Admin.NET.Core;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;



namespace Admin.NET.Application
{
    /// <summary>
    /// APP任务管理
    /// </summary>
    [Route("api/taskmanager")]
    [ApiDescriptionSettings("APP任务管理", Name = "TaskManager", Order = 100)]
    public class TaskService : IDynamicApiController, ITaskService, IScoped
    {
        /// <summary>
        /// 发布任务
        /// </summary>
        /// <param name="taskPublish"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<object> PostTaskPublish(TaskPublishDto taskPublish)
        {
            var pt = taskPublish.Adapt<Plan_Task>();
            pt.TaskStatus = 1;
            var en = await Db.GetRepository<Plan_Task>().InsertNowAsync(pt);
            await InsertTaskRecord(en);
            return en.Entity.Id;
        }
        /// <summary>
        /// 任务执行
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public async Task<object> PostTaskDone(TaskDoneDto state)
        {
            var pt = state.Adapt<Plan_Task>();
            pt.TaskStatus = 2;
            var en = await Db.GetRepository<Plan_Task>().UpdateIncludeNowAsync(pt, new[]
            { nameof(Plan_Task.TaskStatus),nameof(Plan_Task.QuestionType),
            nameof(Plan_Task.SceneImgIdList),nameof(Plan_Task.PatrolInspection) });
            await InsertTaskRecord(en);
            return en.Entity.Id;
        }
        /// <summary>
        /// 上传现场图片
        /// </summary>
        /// <param name="SceneImgList"></param>
        /// <returns></returns>
        public async Task<object> PostTaskDoneFile(List<IFormFile> SceneImgList)
        {
            string filelist = string.Empty;
            string path = "Upload/SceneImg";
            foreach (var file in SceneImgList)
            {
                var pt = new Plan_Target();
                var fileSuffix = Path.GetExtension(file.FileName).ToLower(); // 文件后缀
                var finalName = pt.Id + fileSuffix; // 生成文件的最终名称
                var key = string.Concat(path, "/", finalName);
                pt.IMG = key;
                var stream = file.OpenReadStream();
                qiniuHelper.UploadFile(stream, key);
                pt.InsertNow();
                filelist += $"{pt.Id},";
            }
            return filelist;
        }

        private static async Task InsertTaskRecord(EntityEntry<Plan_Task> en, bool IsRecordRemarks = false)
        {
            Plan_Task_Record plan_Task_Record = new Plan_Task_Record();
            plan_Task_Record.PlanTaskId = en.Entity.Id;
            plan_Task_Record.TaskStatus = en.Entity.TaskStatus;
            if (IsRecordRemarks)
                plan_Task_Record.RecordRemarks = en.Entity.Remarks;
            await Db.GetRepository<Plan_Task_Record>().InsertNowAsync(plan_Task_Record);
        }

        /// <summary>
        /// 任务列表
        /// </summary>
        /// <param name="roleType"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>

        public async Task<List<TaskListDto>> GetTaskList([FromQuery] string roleType, [FromQuery] int pageIndex = 1, [FromQuery] int pageSize = 1)
        {
            var list = (from p in Db.GetRepository<Plan_Task>().AsQueryable()
                        join d in Db.GetRepository<PlanInfo>().AsQueryable() on p.PlandId equals d.Id
                        where roleType.Contains(p.TaskStatus.ToString())
                        select new
                        {
                            Id = p.Id,
                            PlanName = d.PlanName,
                            CreatedTime = p.CompleteTime,
                            TaskStatus = p.TaskStatus,
                            ImplementUserIdList = p.ImplementUserIdList,
                            TargetIdStr = p.TargetIdList
                        }).Skip(pageSize * (pageIndex - 1)).Take(pageSize);
            var ltimg = list.Adapt<List<TaskListDto>>();
            foreach (var item in ltimg)
            {
                item.TargetIdList = Db.GetRepository<Plan_Target>().Where(s => list.FirstOrDefault(t => t.Id == item.Id).TargetIdStr.Contains(s.Id.ToString())).Select(t => qiniuHelper.GetImg(t.IMG)).ToList();
            }
            return ltimg;
        }
        /// <summary>
        /// 任务审核
        /// </summary>
        /// <param name="Review"></param>
        /// <returns></returns>0
        public async Task<object> PostTaskReview(TaskReviewDto Review)
        {
            var pt = Review.Adapt<Plan_Task>();
            if (Review.TaskStatus == 3)
            {
                pt.TaskStatus = 5;
                var en = Db.GetRepository<Plan_Task>().UpdateIncludeNow(pt, new[]
                {nameof(Plan_Task.TaskStatus)});
                en.Entity.TaskStatus = 3;
                en.Entity.Remarks = Review.RecordRemarks;
                await InsertTaskRecord(en,true);
                en.Entity.TaskStatus = 5;
                await InsertTaskRecord(en);
                return en.Entity.Id;
            }
            else
            {
                pt.TaskStatus = 1;
                var en = Db.GetRepository<Plan_Task>().UpdateIncludeNow(pt, new[]
                {nameof(Plan_Task.TaskStatus)});
                en.Entity.TaskStatus = 4;
                en.Entity.Remarks = Review.RecordRemarks;
                await InsertTaskRecord(en, true);
                en.Entity.TaskStatus = 1;
                await InsertTaskRecord(en);
                return en.Entity.Id;
            }

        }
        /// <summary>
        /// 任务详情获取
        /// </summary>
        /// <param name="TaskId"></param>
        /// <returns></returns>
        public async Task<TaskDetailDto> GetTaskDetail([FromQuery] long TaskId)
        {
            var en = await Db.GetRepository<Plan_Task>().FirstOrDefaultAsync(s => s.Id == TaskId);
            if (en == null)
                return null;
            var td = new TaskDetailDto()
            {
                Id = en.Id,
                CompleteTime = en.CompleteTime,
                Remarks = en.Remarks,
                TaskStatus = en.TaskStatus,
                ImplementUserIdList = en.ImplementUserIdList,
                TargetIdList = Db.GetRepository<Plan_Target>().Where(s => en.TargetIdList.Contains(s.Id.ToString())).Select(t => qiniuHelper.GetImg(t.IMG)).ToList(),
                SceneImgIdList = Db.GetRepository<Plan_Target>().Where(s => en.SceneImgIdList.Contains(s.Id.ToString())).Select(t => qiniuHelper.GetImg(t.IMG)).ToList(),
            };
            var tr = Db.GetRepository<Plan_Task_Record>().Where(s => s.PlanTaskId == TaskId&&"34".Contains(s.TaskStatus.ToString())).OrderByDescending(s=>s.CreatedTime).Take(1).ToList();
            if (tr.Count==1)
                td.RecordRemarks = tr[0].RecordRemarks;
            return td;
        }
        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="planId"></param>
        /// <returns></returns>
        public async Task<object> GetTaskFake([FromQuery] long TaskId)
        {
            var List = Db.GetRepository<Plan_Task>().FirstOrDefaultAsync(s=>s.Id==TaskId).Adapt<TaskDetailDto>();
            return List;
        }
    }
}
